var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.static('../Projiect/public/touxiang'))
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// 加载CORS模块
const cors = require('cors');


//配置multer中间件
const multer = require('multer')
obj = multer.diskStorage({
  destination : function(req, file, cb){ //指定目录
    cb(null, 'upload')
  },
  filename : function (req, file, cb){ // 指定文件名
    // console.log(uuid.v1())
    // console.log(uuid.v4())
    let name = file.originalname
    // name:  abcd.jpg    xxxdfdd.zip
    let ext = name.substr(name.lastIndexOf('.'))
    cb(null, uuid.v4() + ext+'.jpg')
  }
})
const uploadTools = multer({
  storage : obj
})
const uuid = require('uuid')

//跨域访问
app.use(cors({
  origin: ['http://localhost:8080', 'http://127.0.0.1:8080']
}));

// 静态资源托管upload目录
app.use(express.static('upload'))

//接收请求



app.post('/upload',
  uploadTools.array('uploadFile'), (req, res)=>{
    console.log(req);
    // console.log(req.body);
    
    // console.log(req.body.b)
     console.log(req.files)
    console.log(req.files[0].filename)
    //  let timg=req.files[0].filename;
     
    res.send(req.files[0].filename)
})


app.use('/', indexRouter);

//接收请求
app.post('/upload',
  uploadTools.array('uploadFile'), (req, res)=>{
    console.log(req.files)
    res.send(req.files)
})


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
